package com.ias.agdis_r.activity;

import android.app.ActionBar;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
//import android.support.v4.app.Fragment;
import androidx.fragment.app.Fragment;
//import android.support.v4.app.FragmentManager;
import androidx.fragment.app.FragmentManager;
//import android.support.v4.app.FragmentTransaction;
import androidx.fragment.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.task.LuggageBarCode;
import com.ias.agdis_r.db.BoxDBHelper;
import com.ias.agdis_r.fragment.task.LuggageBarCodeFinish;
import com.ias.agdis_r.fragment.task.LuggageBarCodeUploading;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.view.BadgeView;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xr.g on 2018/2/6.
 */

public class LuggageBarCodeActivity extends BaseFragmentActivity {
    public static String refreshTabUploading = "refreshTabUploading";
    public static String refreshTabFinish = "refreshTabFinish";
    private ActionBar actionBar;
    private TextView actionBarTitle;
    private String tnb, fke, flo, fln, aod;
    private boolean able_commit = true;
    private int currentActivePageIndex = -1;
    private FragmentManager fragmentManager = getSupportFragmentManager();
    private TextView tvUploading, tvFinish;
    private BaseFragment fragUploading, fragFinish;
    private BadgeView bvUploading, bvFinish;
    private int countUploading, countFinish;
    private LinearLayout llTabUploading, llTabFinish;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_luggagebarcode);
        actionBar = getActionBar();
        initActionbar();
        tnb = getIntent().getStringExtra("tnb");
        fke = getIntent().getStringExtra("fke");
        flo = getIntent().getStringExtra("flo");
        fln = getIntent().getStringExtra("fln");
        aod = getIntent().getStringExtra("aod");
        initBlueTooth();
        initView();
        resetDate();
    }

    private void initActionbar() {
        actionBar.setCustomView(LayoutInflater.from(LuggageBarCodeActivity.this)
                .inflate(R.layout.actionbar_back_and_home, null));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBarTitle = (TextView) findViewById(R.id.txt_title);
        ImageView back = (ImageView) findViewById(R.id.action_back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        ImageView home = (ImageView) findViewById(R.id.action_home);
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LuggageBarCodeActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        actionBarTitle.setText(getString(R.string.barcodeScane));
    }

    private void initBlueTooth() {
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    private void resetDate() {
        BoxDBHelper boxDBHelper = new BoxDBHelper(this);
        countUploading = boxDBHelper.getUploadingLuggageBarCodeCount(tnb);
        countFinish = boxDBHelper.getFinishLuggageBarCodeCount(tnb);
        boxDBHelper.closeDB();
        if (null != bvUploading && null != bvFinish) {
            bvUploading.setBadgeCount(countUploading);
            bvFinish.setBadgeCount(countFinish);
        }
    }

    private void initView() {
        fragUploading = (BaseFragment) fragmentManager.findFragmentById(R.id.frag_uploading);
        LuggageBarCodeUploading luggageBarCodeUploading = (LuggageBarCodeUploading) fragUploading;
        luggageBarCodeUploading.setTnb(tnb);
        fragFinish = (BaseFragment) fragmentManager.findFragmentById(R.id.frag_finish);
        LuggageBarCodeFinish luggageBarCodeFinish = (LuggageBarCodeFinish) fragFinish;
        luggageBarCodeFinish.setTnb(tnb);
        tvUploading = (TextView) findViewById(R.id.tv_uploading);
        tvFinish = (TextView) findViewById(R.id.tv_finish);
        final EditText etBarCodeNum = (EditText) findViewById(R.id.et_luggageBarCodeNum);
        final Button btn = (Button) findViewById(R.id.btn_luggageBarCodeAdd);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String barCodeNum = etBarCodeNum.getText().toString().trim();
                if (S.isEmpty(barCodeNum)) {
                    EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.barcodeEmpty), false);
                } else if (barCodeNum.length() > 30) {
                    EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.barcodeOverLength), false);
                }
                boolean succeed = saveLuggageBarCode(barCodeNum);
                if (succeed) {
                    resetDate();
                    updateUI(refreshTabUploading);
                }
                etBarCodeNum.setText("");
            }
        });
        etBarCodeNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 1) {
                    String sub = s.subSequence(s.length() - 1, s.length()).toString();
                    if ("\n".equals(sub)) {
                        String str = s.toString().trim();
                        if (S.isNotEmpty(str) && str.length() < 10) {
                            EffectManager.getInstance().vibrate();
                            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.barcodeError), false);
                            etBarCodeNum.setText("");
                        } else {
                            btn.performClick();
                        }
                    }
                }
            }
        });
        llTabUploading = (LinearLayout) findViewById(R.id.id_tab_uploading);
        llTabUploading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPage(0);
            }
        });
        llTabFinish = (LinearLayout) findViewById(R.id.id_tab_finish);
        llTabFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPage(1);
            }
        });
        bvUploading = new BadgeView(this);
        bvFinish = new BadgeView(this);
        llTabUploading.addView(bvUploading);
        llTabFinish.addView(bvFinish);
        selectPage(0);
    }

    public void selectPage(int index) {
        //如果不能切换时，不进行切换
        if (!able_commit) {
            return;
        }
        // 索引不合法
        if (index < 0 || index > 1) {
            return;
        }
        // 为当前页直接返回
        if (currentActivePageIndex == index) {
            return;
        }
        currentActivePageIndex = index;
        List<Fragment> fragments = new ArrayList<Fragment>();
        Fragment fragmentUploading = fragmentManager.findFragmentById(R.id.frag_uploading);
        Fragment fragmentFinish = fragmentManager.findFragmentById(R.id.frag_finish);
        fragments.add(fragmentUploading);
        fragments.add(fragmentFinish);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if (i == index) {
                transaction.show(fragments.get(i));
            } else {
                transaction.hide(fragments.get(i));
            }
        }
        transaction.commit();
        if (null != tvUploading && null != tvFinish) {
            tvUploading.setTextColor(getResources().getColor(0 == index ? R.color.green : R.color.black));
            tvFinish.setTextColor(getResources().getColor(1 == index ? R.color.green : R.color.black));
            if (0 == index) {
                llTabUploading.setBackgroundColor(getResources().getColor(R.color.white));
                llTabFinish.setBackgroundDrawable(null);
            } else {
                llTabUploading.setBackgroundDrawable(null);
                llTabFinish.setBackgroundColor(getResources().getColor(R.color.white));
            }
        }
    }

    private boolean saveLuggageBarCode(String barCodeNum) {
        long i = -1;
        if (S.isNotEmpty(barCodeNum)) {
            LuggageBarCode luggageBarCode = new LuggageBarCode();
            luggageBarCode.setFkey(fke);
            luggageBarCode.setFlop(flo);
            luggageBarCode.setFlno(fln);
            luggageBarCode.setAdid(aod);
            luggageBarCode.setTnb(tnb);
            luggageBarCode.setEnb(JavaBeanManager.getInstance().getUserinfo().getEnb());
            luggageBarCode.setBarcode(barCodeNum);
            luggageBarCode.setScanTime(S.getNowTime3());
            luggageBarCode.setState(LuggageBarCode.STATE_ADD);
            BoxDBHelper dbHelper = new BoxDBHelper(LuggageBarCodeActivity.this);
            i = dbHelper.saveLuggageBarCode(luggageBarCode, true);
            if (i == -2) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.barcodeDuplicate), false);
            }
            if (i == -1) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.barcodeSaveFailed), false);
            }
            dbHelper.closeDB();
        }
        return i != -1 && i != -2;
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        if (MessageModel.ULBC.equals(serviceId) || MessageModel.DLBC.equals(serviceId)
                || MessageModel.QLBC.equals(serviceId)) {
            resetDate();
            fragUploading.updateUI(serviceId);
            fragFinish.updateUI(serviceId);
        }
    }

    @Override
    protected void updateUI(String tag) {
        fragUploading.updateUI(tag);
        fragFinish.updateUI(tag);
    }

    @Override
    protected void onStart() {
        super.onStart();
        able_commit = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        able_commit = true;
    }

    @Override
    protected void onStop() {
        able_commit = false;
        super.onStop();
    }

    @Override
    protected void onPause() {
        able_commit = false;
        super.onPause();
    }

    public Map<String, String> getDate() {
        Map<String, String> map = new LinkedHashMap<>();
        map.put("tnb", tnb);
        map.put("fke", fke);
        map.put("flo", flo);
        map.put("fln", fln);
        map.put("aod", aod);
        return map;
    }
}
